from django.shortcuts import render

from django.views import View
from django_redis import get_redis_connection
from django import http
from random import randint

from csdp.libs.captcha.captcha import captcha
from csdp.utils.response_code import RETCODE
# from csdp.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from . import constants
import logging

logger = logging.getLogger('django')

# Create your views here.

class ImageCodeView(View):
    def get(self, request, uuid):
        name ,text, image_code = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(uuid, 300, text)
        return http.HttpResponse(image_code, content_type = 'image/png')


class SMSCodeView(View):
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '短信发送频繁。'})
        query_dict = request.GET
        image_code_client = query_dict.get('image_code')
        uuid = query_dict.get('uuid')
        if all([image_code_client, uuid]) is False:
            return http.HttpResponseForbidden('参数错误。')
        image_code_server = redis_conn.get(uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码填写错误。'})
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期。'})
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)
        send_sms_code.delay(mobile, sms_code)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRE, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SMS_CODE_FLAG_EXPIRE, 1)
        pl.execute()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
